package cn.edu.fzu.homemaking.controller;

import cn.edu.fzu.homemaking.common.PageVO;
import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.domain.entity.DateCount;
import cn.edu.fzu.homemaking.domain.entity.Order;
import cn.edu.fzu.homemaking.domain.entity.Statistics;
import cn.edu.fzu.homemaking.domain.enums.CommentStatusEnum;
import cn.edu.fzu.homemaking.domain.enums.OrderStatusEnum;
import cn.edu.fzu.homemaking.domain.vo.OrderVo;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.service.OrderService;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/order/auth")
@Api(tags = "订单管理")
public class OrderController {
    @Resource
    private OrderService orderService;

    @PostMapping("/insert")
    @ApiOperation(value = "生成订单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", required = true),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "demandId", value = "需求id"),
            @ApiImplicitParam(name = "serverId", value = "服务id"),
            @ApiImplicitParam(name = "description", value = "描述=若由公司接需求单生成订单，则为需求单的需求；若由顾客下单服务，则为服务名称",required = true),
            @ApiImplicitParam(name = "customerName", value = "顾客名",required = true),
            @ApiImplicitParam(name = "address", value = "服务地址", required = true),
            @ApiImplicitParam(name = "phone", value = "联系电话", required = true),
            @ApiImplicitParam(name = "email", value = "邮箱地址", required = true),
            @ApiImplicitParam(name = "startTime", value = "约定服务时间",required = true),
            @ApiImplicitParam(name = "price", value = "服务价格（服务单价，若根据需求单生成的订单，则为需求单上的价格）", required = true),
            @ApiImplicitParam(name = "qty", value = "数量", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result insert(Long companyId, Long userId, Long demandId, Long serverId, String description, String customerName,
                         String address, String phone, String email, String startTime, BigDecimal price, Integer qty){
        if (demandId == null && serverId == null){
            throw new ServiceException("表单填写不正确");
        }
        orderService.insert(companyId, userId, demandId, serverId, description, customerName, address, phone, email, startTime, price, qty);
        return new Result(RetCode.SUCCESS,"生成订单成功");
    }

    @GetMapping("list")
    @ApiOperation(value = "获取订单列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "demandId", value = "需求id"),
            @ApiImplicitParam(name = "serverId", value = "服务id"),
            @ApiImplicitParam(name = "startTime", value = "开始时间（服务约定时间）"),
            @ApiImplicitParam(name = "endTime", value = "结束时间（服务约定时间）"),
            @ApiImplicitParam(name = "status", value = "订单状态"),
            @ApiImplicitParam(name = "commentStatus", value = "订单评价状态"),
            @ApiImplicitParam(name = "pageNum", required = true),
            @ApiImplicitParam(name = "pageSize", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result list(Long demandId, Long serverId, String startTime, String endTime,
                       OrderStatusEnum status, CommentStatusEnum commentStatus, Integer pageNum,
                       Integer pageSize, HttpServletRequest request){
        Long customerId = (Long) request.getSession().getAttribute(SessionConstant.USER);
        Long companyId = (Long) request.getSession().getAttribute(SessionConstant.COMPANY);
        try(Page<Order> page = PageHelper.startPage(pageNum, pageSize)){
            List<OrderVo> list = orderService.list(companyId, customerId, demandId, serverId, startTime, endTime, status, commentStatus);
            return new Result(new PageVO<>(page.getTotal(),list));
        }
    }

    @GetMapping("selectByOrderId")
    @ApiOperation(value = "根据订单id获取订单",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result selectByOrderId(String orderId){
        Order order = orderService.selectByOrderId(orderId);
        return new Result(order);
    }

    @PostMapping("updateStatus")
    @ApiOperation(value = "更新订单状态", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true),
            @ApiImplicitParam(name = "status", value = "订单状态", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result updateStatus(String orderId, OrderStatusEnum status, HttpServletRequest request){
        Long customerId = (Long) request.getSession().getAttribute(SessionConstant.USER);
        Long companyId = (Long) request.getSession().getAttribute(SessionConstant.COMPANY);
        orderService.updateStatus(orderId, status, customerId, companyId);
        return new Result(RetCode.SUCCESS, "更新订单状态成功");
    }

    @PostMapping("updateCommentStatus")
    @ApiOperation(value = "更新订单评价状态", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true),
            @ApiImplicitParam(name = "status", value = "评价状态", required = true)
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result updateCommentStatus(String orderId, CommentStatusEnum status){
        orderService.updateCommentStatus(orderId, status);
        return Result.SUCCESS;
    }

    @GetMapping("listByOrderIds")
    @ApiOperation(value = "获取多个订单信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderIds", value = "订单id（列表）",required = true),
            @ApiImplicitParam(name = "startTime", value = "开始时间（约定服务时间）"),
            @ApiImplicitParam(name = "endTime", value = "结束时间（约定服务时间）"),
            @ApiImplicitParam(name = "status",value = "订单状态")
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result listByOrderIds(List<String> orderIds, String startTime, String endTime, OrderStatusEnum status,
                                 HttpServletRequest request){
        List<Order> list = orderService.listByOrderIds(orderIds, startTime, endTime, status);
        return new Result(list);
    }

    @GetMapping("getUnPayMoney")
    @ApiOperation(value = "获取用户待支付的金额",httpMethod = "GET")
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result getUnPayMoney(HttpServletRequest request){
        Long customerId = (Long)request.getSession().getAttribute(SessionConstant.USER);
        BigDecimal money = orderService.getUnPayMoney(customerId);
        return new Result(money);
    }

    @GetMapping("count")
    @ApiOperation(value = "订单统计概览", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间（订单创建时间）"),
            @ApiImplicitParam(name = "endTime", value = "结束时间（订单创建时间）")
    })
    @ApiResponse(code = 200, message = "", response = Result.class)
    public Result count(String startTime, String endTime, HttpServletRequest request){
        Long companyId = (Long) request.getSession().getAttribute(SessionConstant.COMPANY);
        if (companyId == null&& !Objects.equals(request.getSession().getAttribute(SessionConstant.USER_TYPE),SessionConstant.SYS_USER)){
            throw new ServiceException("非公司和系统管理人员，无法获取统计信息");
        }
        Statistics statistics = orderService.count(startTime, endTime, companyId);
        return new Result(statistics);
    }

    @GetMapping("countByMonth")
    @ApiOperation(value = "按月统计订单", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间（订单创建时间）",required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间（订单创建时间）",required = true)
    })
    public Result countByMonth(String startTime, String endTime, HttpServletRequest request){
        Long companyId = (Long)request.getSession().getAttribute(SessionConstant.COMPANY);
        if (companyId == null&& !Objects.equals(request.getSession().getAttribute(SessionConstant.USER_TYPE),SessionConstant.SYS_USER)){
            throw new ServiceException("非公司和系统管理人员，无法获取统计信息");
        }
        List<DateCount> list = orderService.countByMonth(startTime, endTime, companyId);
        return new Result(list);
    }

    @GetMapping("countByDay")
    @ApiOperation(value = "按天统计订单", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间（订单创建时间）",required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间（订单创建时间）",required = true)
    })
    public Result countByDay(String startTime, String endTime, HttpServletRequest request){
        Long companyId = (Long)request.getSession().getAttribute(SessionConstant.COMPANY);
        if (companyId == null && !Objects.equals(request.getSession().getAttribute(SessionConstant.USER_TYPE),SessionConstant.SYS_USER)){
            throw new ServiceException("非公司和系统管理人员，无法获取统计信息");
        }
        List<DateCount> list = orderService.countByDay(startTime, endTime, companyId);
        return new Result(list);
    }
}
